package com.robotserver.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.robotserver.orders.common.CsjApiUtil;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.common.Math;
import com.robotserver.orders.entity.DyOrders;
import com.robotserver.orders.entity.DyTokens;
import com.robotserver.orders.mapper.DyOrdersMapper;
import com.robotserver.orders.mapper.DyTokensMapper;
import com.robotserver.orders.mapper.SysSettingMapper;
import com.robotserver.orders.service.DyOrderCsjSyncService;
import com.robotserver.orders.vo.DyOrderCsjTimeVO;
import com.robotserver.orders.vo.dycsjorder.DyOrderCsjResult;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.TreeMap;

/**
 * @Auther: jianghan
 * @Date: 2020/12/2 14:05
 * @Description:
 */
@Service
public class DyOrderCsjSyncServiceImpl implements DyOrderCsjSyncService {

    private static Logger logger = LoggerFactory.getLogger(DyOrderCsjSyncServiceImpl.class);

    String csjDyUrl = "https://ecom.pangolin-sdk-toutiao.com/order/search";

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private DyTokensMapper dyTokensMapper;
    @Autowired
    private SysSettingMapper sysSettingMapper;
    @Autowired
    private DyOrdersMapper dyOrdersMapper;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public void syncOpenUnitOrder(List<DyOrderCsjTimeVO> dyOrderCsjTimeVOS, DyTokens token, Integer downType) {
        for (DyOrderCsjTimeVO time : dyOrderCsjTimeVOS) {
            syncTimeUnitOrder(time, token, "0", downType); //cursor下一页索引（第一页传“0”）
        }
    }

    @Override
    public void syncTimeUnitOrder(DyOrderCsjTimeVO time, DyTokens dyTokens, String cursor, Integer downType) {
        try {

            DyOrderCsjResult dyOrderCsjResult = getOrders(time.getBeginTime(), time.getEndTime(), cursor, downType, null, dyTokens);
            if (dyOrderCsjResult != null && dyOrderCsjResult.getData() != null && dyOrderCsjResult.getData().getOrders() != null && dyOrderCsjResult.getData().getOrders().size() > 0) {
                // 处理订单入库
                ordersAdd(dyOrderCsjResult.getData().getOrders(), dyTokens);
                //下页的索引
                String cursor_next = dyOrderCsjResult.getData().getCursor();
                syncTimeUnitOrder(time, dyTokens, cursor_next, downType);
            }
        } catch (Exception e) {
            logger.error("dyOrderCsj sync order err:{}", e.getMessage());
        }
    }

    @Override
    public void ordersAdd(List<DyOrderCsjResult.DyOrderCsj> orderInfoList, DyTokens dyTokens) {
        for (DyOrderCsjResult.DyOrderCsj orderInfo : orderInfoList) {
            try {

                String extInfo = orderInfo.getExternalInfo();
                if (StringUtils.isBlank(extInfo)) {
                    continue; //没有自定义参数，不是我们平台的订单
                }

                if (!extInfo.startsWith(dyTokens.getAppId() + "_")) {
                    //continue; //格式不是以appID_开头，不是我们平台的订单
                }

                int bizstatus = bizStatus(orderInfo.getFlowPoint());
                if (bizstatus == -1) {
                    // continue;
                }

                int now = DateUtil.getNowTime();

                // 根据订单号查询商品是否存在
                DyOrders dyOrders = dyOrdersMapper.getByOrderId(orderInfo.getOrderId());
                if (dyOrders == null) {

                    logger.info("---DY orders csj add;  orderId:{}, productId:{}, status:{}, modifytime:{}", new Object[]{orderInfo.getOrderId(), orderInfo.getProductId(), orderInfo.getFlowPoint(), orderInfo.getUpdateTime()});

                    dyOrders = new DyOrders();
                    dyOrders.setId(IdWorker.getId());
                    dyOrders.setOrderId(orderInfo.getOrderId());
                    dyOrders.setConfirmTime(DateUtil.getStrTime(orderInfo.getConfirmTime()));
                    dyOrders.setMaterialId(null);
                    dyOrders.setAuthorBuyinId(null);
                    dyOrders.setProductId(orderInfo.getProductId());
                    dyOrders.setProductName(orderInfo.getProductName());
                    dyOrders.setProductImg(orderInfo.getProductImg());
                    dyOrders.setAuthorAccount(orderInfo.getAuthorAccount());
                    dyOrders.setShopName(null);
                    dyOrders.setTotalPayAmount(Math.div(orderInfo.getTotalPayAmount() == null ? 0 : orderInfo.getTotalPayAmount(), 100));
                    dyOrders.setFlowPoint(orderInfo.getFlowPoint());
                    dyOrders.setModifyTime(DateUtil.getStrTime(orderInfo.getUpdateTime()));
                    dyOrders.setPaySuccessTime(DateUtil.getStrTime(orderInfo.getPaySuccessTime()));
                    dyOrders.setSettleTime(DateUtil.getStrTime(orderInfo.getSettleTime()));
                    dyOrders.setPayGoodsAmount(Math.div(orderInfo.getPayGoodsAmount() == null ? 0 : orderInfo.getPayGoodsAmount(), 100));
                    dyOrders.setSettledGoodsAmount(Math.div(orderInfo.getAdsRealCommission() == null ? 0 : orderInfo.getAdsRealCommission(), 100));
                    dyOrders.setShopId(null);

                    //分销订单相关参数
                    dyOrders.setPid(null);
                    dyOrders.setExternalInfo(orderInfo.getExternalInfo());
                    dyOrders.setMediaTypeName(orderInfo.getMediaTypeName());
                    dyOrders.setItemNum(1L);
                    dyOrders.setRefundTime(DateUtil.getStrTime(orderInfo.getRefundTime()));
                    dyOrders.setAdsEstimatedCommission(Math.div(orderInfo.getEstimatedCommission() == null ? 0 : orderInfo.getEstimatedCommission(), 100));
                    dyOrders.setAdsRealCommission(Math.div(orderInfo.getAdsRealCommission() == null ? 0 : orderInfo.getAdsRealCommission(), 100));
                    dyOrders.setAuthorShortId(null);
                    dyOrders.setAdsPromotionRate(Math.div(orderInfo.getSplitRate() == null ? 0 : orderInfo.getSplitRate(), 100));
                    dyOrders.setMediaType(null);
                    dyOrders.setAdsActivityId(null);
                    dyOrders.setAdsEstimatedTechServiceFee(Math.div(orderInfo.getEstimatedTechServiceFee() == null ? 0 : orderInfo.getEstimatedTechServiceFee(), 100));
                    dyOrders.setAdsFansType(null);
                    dyOrders.setProductActivityId(null);
                    dyOrders.setBizStatus(bizstatus);
                    dyOrders.setCreateTime(now);
                    dyOrders.setUpdateTime(now);
                    dyOrders.setTokenType(1); //穿山甲抖音订单
                    dyOrders.setTokenId(orderInfo.getAppId());

                    DyOrderCsjResult.ColonelOrderInfo colonelOrderInfo = orderInfo.getColonelOrderInfo();
                    if(colonelOrderInfo != null){
                        dyOrders.setActivityId(colonelOrderInfo.getActivityId() == null ? 0 : colonelOrderInfo.getActivityId());
                        dyOrders.setInstitutionId(colonelOrderInfo.getInstitutionId() == null ? 0 : colonelOrderInfo.getInstitutionId());
                        dyOrders.setInstitutionName(colonelOrderInfo.getInstitutionName());
                    }else{
                        dyOrders.setActivityId(null);
                        dyOrders.setInstitutionId(0L);
                        dyOrders.setInstitutionName(null);
                    }

                    //抖音订单增加
                    dyOrdersMapper.add(dyOrders);

                } else {
                    logger.info("---DY orders update;  orderId:{}, productId:{}, status:{}, modifytime:{}", new Object[]{orderInfo.getOrderId(), orderInfo.getProductId(), orderInfo.getFlowPoint(), orderInfo.getUpdateTime()});

                    dyOrders.setOrderId(orderInfo.getOrderId());
                    dyOrders.setConfirmTime(DateUtil.getStrTime(orderInfo.getConfirmTime()));
                    dyOrders.setMaterialId(null);
                    dyOrders.setAuthorBuyinId(null);
                    dyOrders.setProductId(orderInfo.getProductId());
                    dyOrders.setProductName(orderInfo.getProductName());
                    dyOrders.setProductImg(orderInfo.getProductImg());
                    dyOrders.setAuthorAccount(orderInfo.getAuthorAccount());
                    dyOrders.setShopName(null);
                    dyOrders.setTotalPayAmount(Math.div(orderInfo.getTotalPayAmount() == null ? 0 : orderInfo.getTotalPayAmount(), 100));
                    dyOrders.setFlowPoint(orderInfo.getFlowPoint());
                    dyOrders.setModifyTime(DateUtil.getStrTime(orderInfo.getUpdateTime()));
                    dyOrders.setPaySuccessTime(DateUtil.getStrTime(orderInfo.getPaySuccessTime()));
                    dyOrders.setSettleTime(DateUtil.getStrTime(orderInfo.getSettleTime()));
                    dyOrders.setPayGoodsAmount(Math.div(orderInfo.getPayGoodsAmount() == null ? 0 : orderInfo.getPayGoodsAmount(), 100));
                    dyOrders.setSettledGoodsAmount(Math.div(orderInfo.getAdsRealCommission() == null ? 0 : orderInfo.getAdsRealCommission(), 100));
                    dyOrders.setShopId(null);

                    //分销订单相关参数
                    dyOrders.setPid(null);
                    dyOrders.setExternalInfo(orderInfo.getExternalInfo());
                    dyOrders.setMediaTypeName(orderInfo.getMediaTypeName());

                    dyOrders.setItemNum(1L);
                    dyOrders.setRefundTime(DateUtil.getStrTime(orderInfo.getRefundTime()));
                    dyOrders.setAdsEstimatedCommission(Math.div(orderInfo.getEstimatedCommission() == null ? 0 : orderInfo.getEstimatedCommission(), 100));
                    dyOrders.setAdsRealCommission(Math.div(orderInfo.getAdsRealCommission() == null ? 0 : orderInfo.getAdsRealCommission(), 100));
                    dyOrders.setAuthorShortId(null);
                    dyOrders.setAdsPromotionRate(Math.div(orderInfo.getSplitRate() == null ? 0 : orderInfo.getSplitRate(), 100));
                    dyOrders.setMediaType(null);
                    dyOrders.setAdsActivityId(null);
                    dyOrders.setAdsEstimatedTechServiceFee(Math.div(orderInfo.getEstimatedTechServiceFee() == null ? 0 : orderInfo.getEstimatedTechServiceFee(), 100));
                    dyOrders.setAdsFansType(null);
                    dyOrders.setProductActivityId(null);
                    dyOrders.setBizStatus(bizstatus);
                    dyOrders.setUpdateTime(now);
                    dyOrders.setTokenType(1); //穿山甲抖音订单
                    dyOrders.setTokenId(dyTokens.getAppId());

                    DyOrderCsjResult.ColonelOrderInfo colonelOrderInfo = orderInfo.getColonelOrderInfo();
                    if(colonelOrderInfo != null){
                        dyOrders.setActivityId(colonelOrderInfo.getActivityId() == null ? 0 : colonelOrderInfo.getActivityId());
                        dyOrders.setInstitutionId(colonelOrderInfo.getInstitutionId() == null ? 0 : colonelOrderInfo.getInstitutionId());
                        dyOrders.setInstitutionName(colonelOrderInfo.getInstitutionName());
                    }else{
                        dyOrders.setActivityId(null);
                        dyOrders.setInstitutionId(0L);
                        dyOrders.setInstitutionName(null);
                    }

                    //抖音订单修改
                    dyOrdersMapper.update(dyOrders);

                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("--抖音订单下载失败--" + orderInfo.getOrderId() + " err:{}", e);
            }
        }
    }

    @Async("taskExecutor")
    @Override
    public void threadSyncOrder_consumer(List<DyOrderCsjTimeVO> dyOrderTimeVOS, DyTokens token, Integer downType) {
        syncOpenUnitOrder(dyOrderTimeVOS, token, downType);
    }

    private int bizStatus(String orderSubStatusName) {
        switch (orderSubStatusName) {
            case "PAY_SUCC":
                return 0;
            case "SETTLE":
                return 1;
            case "CONFIRM":
                return 1;
            case "REFUND":
                return 3;
        }
        return -1;
    }

    /**
     * @param timeType 1-付款时间；4-更新时间
     * @return com.alibaba.fastjson.JSONObject
     * @author jitwxs
     * @date 2024/3/21 17:19
     */
    public DyOrderCsjResult getOrders(long startTime, long endTime, String cursor, int timeType, List<String> orderIds, DyTokens dyTokens) {
        TreeMap<String, Object> data = new TreeMap<>();
        if (CollectionUtils.isEmpty(orderIds)) {
            data.put("size", 40L);
            data.put("cursor", cursor);
            data.put("start_time", startTime);
            data.put("end_time", endTime);
            data.put("order_type", 1);
            String time_type = "update"; //默认为订单付款时间
            if (timeType == 1) { //付款时间
                time_type = "pay";
            }
            data.put("time_type", time_type);
        } else {
            data.put("order_type", 1);
            data.put("order_ids", orderIds);
        }
        CsjApiUtil.RequestBody params = CsjApiUtil.getParams(dyTokens.getAppId(), dyTokens.getAccessToken(), data);

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<CsjApiUtil.RequestBody> request = new HttpEntity<>(params, headers);
            ResponseEntity<JSONObject> response = restTemplate.exchange(csjDyUrl, HttpMethod.POST, request, JSONObject.class);
            if (response != null && response.getBody() != null) {
                JSONObject respData = response.getBody();
                DyOrderCsjResult dyOrderCsjResult = JSONObject.parseObject(respData.toJSONString(), DyOrderCsjResult.class);
                return dyOrderCsjResult;
            }
        } catch (Exception e) {
            logger.error("err:", e);
        }
        return null;
    }

}
